package cn.com.open.itembank.common;

import cn.com.open.itembank.common.enums.DifficultyType;
import cn.com.open.itembank.utils.StringUtil;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by lucky on 2017/7/21.
 */
public class Function {

    private Function() {
    }

    /**
     * 获取访问者IP地址
     * <p>在一般情况下使用Request.getRemoteAddr()即可，但是经过nginx等反向代理软件后，这个方法会失效。</p>
     * <p>本方法先从Header中获取X-Real-IP，如果不存在再从X-Forwarded-For获得第一个IP(用,分割)。</p>
     * <p>如果还不存在则调用Request.getRemoteAddr()。</p>
     *
     * @param request the request
     * @return ip ip
     */
    public static String getIp(HttpServletRequest request) {
        String ip = request.getHeader("X-Real-IP");
        if (!StringUtil.isEmpty(ip) && !"unknown".equalsIgnoreCase(ip)) {
            return ip;
        }
        ip = request.getHeader("X-Forwarded-For");
        if (!StringUtil.isEmpty(ip) && !"unknown".equalsIgnoreCase(ip)) {
            int index = ",".indexOf(ip);
            if (index != -1) {
                return ip.substring(0, index);
            } else {
                return ip;
            }
        } else {
            return request.getRemoteAddr();
        }
    }

    //region 根据难度枚举得到难度数字范围，map的key表示min,value表示max

    /**
     * 根据难度枚举得到难度数字范围，map的key表示min,value表示max.
     *
     * @param type the type
     * @return the difficulty value
     */
    public static Map<Float, Float> getDifficultyValue(DifficultyType type) {
        Map<Float, Float> map = new HashMap<>();

        if (type == DifficultyType.EASY) {
            map.put(0.7f, 1f);
        } else if (type == DifficultyType.NORMAL) {
            map.put(0.4f, 0.6f);
        } else if (type == DifficultyType.HARD) {
            map.put(0f, 0.3f);
        } else {
            map.put(0f, 1f);
        }

        return map;
    }
    //endregion

    //region 根据难度值获得难度范围枚举
    /**
     * 根据难度值获得难度范围枚举.
     *
     * @param difficulty the difficulty
     * @return the difficulty type
     */
    public static DifficultyType getDifficultyType(double difficulty) {
        if (difficulty <= 0.3) {
            return DifficultyType.HARD;
        } else if (difficulty > 0.3 && difficulty <= 0.6) {
            return DifficultyType.NORMAL;
        } else {
            return DifficultyType.EASY;
        }
    }
    //endregion

    //region ASCII转换为char

    /**
     * ASCII转换为char
     *
     * @param ascii the ascii
     * @return char char
     */
    public static char byteAsciiToChar(int ascii) {
        return (char) ascii;
    }

    /**
     * char转换ASCII.
     *
     * @param chars the chars
     * @return the int
     */
    public static int charToAscii(String chars) {
        if (chars.length() > 1) {
            return -1;
        }
        return (int) chars.charAt(0);
    }

    /**
     * 得到大写字母的序号.
     *
     * @param chars the chars
     * @return the upper case index
     */
    public static int getUpperCaseIndex(String chars) {
        int charAscii = charToAscii(chars);
        if (charAscii < 0) {
            return charAscii;
        }
        return charAscii - 65;
    }
    //endregion

    //region 得到文件扩展名

    /**
     * 得到文件扩展名.
     *
     * @param filePath the file path
     * @return the ext name
     */
    public static String getExtName(String filePath) {
        return filePath.substring(filePath.lastIndexOf('.'));
    }
    //endregion

    //region 得到给定路径中的图片文件名

    /**
     * 得到给定路径中的图片文件名.
     *
     * @param orginString the orgin string
     * @return the img file name
     */
    public static String getImgFileName(String orginString) {
        String suffixes = "jpeg|jpg|png";
        Pattern pat = Pattern.compile("[\\w]+[\\.](" + suffixes + ")");//正则判断
        Matcher matcher = pat.matcher(orginString);//条件匹配
        while (matcher.find()) {
            String substring = matcher.group();//截取文件名后缀名
            if (substring.length() > 0) {
                return substring;
            }
        }

        return "";
    }
    //endregion

    //region 正则（筛选图片表格音频）

    /**
     * 正则（筛选图片表格音频）
     *
     * @param str
     * @return
     */
    public static List<String> splitByPattern(String str) {
        List<String> result = new ArrayList<>();
        int lastIndex = 0;
        Pattern pattern = Pattern.compile("(<table[^>]*?>[\\s\\S]*?<\\/table>|<img*?[\\s\\S]*?\\/>|<img*?[\\s\\S]*?>|<media*?[\\s\\S]*?>|<media[^>]*?[\\s\\S]*?><\\/media>|<video*?[\\s\\S]*?>|<video[^>]*?[\\s\\S]*?><\\/video>)");
        Matcher matcher = pattern.matcher(str);
        while (matcher.find()) {
            if (!StringUtil.isEmpty(str.substring(lastIndex, matcher.start()))) {
                result.add(str.substring(lastIndex, matcher.start()));
            }
            result.add(matcher.group());
            lastIndex = matcher.end();
        }
        if (lastIndex < str.length())
            result.add(str.substring(lastIndex));
        else if (lastIndex == 0)
            result.add(str);

        return result;
    }
    //endregion

    //region 通过富文本标签(<img src= */>) 获取下载路径 http:
    /**
     *
     * @param orginString
     * @return
     */
    public static String findPath(String orginString) {
        String patternString = "(?<=(href|src)=)(?<Q>\"|')(?<PATH>.*?)\\k<Q>";
        Pattern p = Pattern.compile(patternString, Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
        Matcher matcher = p.matcher(orginString);
        if (matcher.find()) {
            String fullPath = matcher.group("PATH").replace("", "");
            return fullPath;
        }
        return null;
    }
    //endregion
}
